<?php

/**
* @file
* Contains \Drupal\libsys\Form\Presto2List.
*/

namespace Drupal\libsys\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
* MarcXml to Web concerter
*/
class Presto2List extends FormBase {
	/**
	* {@inheritdoc}
	*/
	public function getFormId() {
		return 'libsys_presto2list';
	}
	
	/*
         * {@inheritdoc}
	*/
	public function buildForm(array $form, FormStateInterface $form_state) {
		$form=[];
		$form['#cache']['max-age'] = 0;
		$form['pageurl']=array(
			'#type'=>'textfield',
			'#title'=>$this->t('Presto Page URL'),
			'#required'=>TRUE,
			'#maxlength'=> 200,
			'#size'=>100,
			'#default_value'=>$_SESSION['next_page']
		);
		$form['hide_duplicated_items']=[
			'#type'=>'checkbox',
			'#title'=>'Automatically hide the items which are duplicated within libsys database.',
			'#default_value'=>TRUE
		];

                $form['actions']['submit'] = [
                        '#type'=>'submit',
                        '#value'=>$this->t('Fetch'),
                ];

		$booklist=$_SESSION['booklist'];
		
		try {
			$rows=[];
			$form['list']=[
				'#type'=>'table',
				'#header'=> [
					'title', 'author', 'publisherName', 'isbn', 'price', 'publishYear'
				],
			];
			$form['list']['#rows']=$booklist;
		} catch (\Exception $e) {
		}

		return $form;
	}

	/**
	* {@inheritdoc}
	*/
	public function validateForm(array &$form, FormStateInterface $form_state) {
	}

	/**
	* {@inheritdoc}
	*/
	public function submitForm(array &$form, FormStateInterface $form_state) {
		$operations=[];
		$pageurl=$form_state->getValue('pageurl');
		if(preg_match('/\/products\//', $pageurl))
			$operations[]=['libsys_presto_to_list', [$pageurl]];
		elseif(preg_match('/\/browse/', $pageurl)||preg_match('/\/search/', $pageurl)) {
			$data = (string) \Drupal::httpClient()->get($pageurl, ['cookies' => $cookieJar])->getBody();
			$doc = new \DOMDocument();
			$doc->loadHTML($data);
			$xpath = new \DOMXpath($doc);

			$elements = $xpath->query('//*[@id="a11y-results"]/div/div/div[1]/div[2]/div[1]/h2/a');

			$urls=[];
			foreach($elements as $element) {
				$operations[]=['libsys_presto_to_list', ['https://www.prestomusic.com'.$element->getAttribute('href')]];
			}
			
			$url=parse_url($form_state->getValue('pageurl'));
			parse_str($url['query'], $query_options);
			$query_options['page']=empty($query_options['page'])?'2':(int)($query_options['page'])+1;
			
			$_SESSION['next_page']=sprintf('%s://%s%s?%s', $url['scheme'], $url['host'], $url['path'], http_build_query($query_options, '', '&'));
		}
		$_SESSION['shouldfilter']=$form_state->getValue('hide_duplicated_items');

		$batch=[
			'operations'=> $operations,
			'finished'=>'libsys_presto_to_list_finished',
			'progressive'=>TRUE,
			'file' => drupal_get_path('module', 'libsys'). '/libsys.batch.inc',
		];
		batch_set($batch);
	}
}
?>

